package com.fly.visit.service;

import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TokenService
{
    private String sysToken;
    
    /**
     * sysToken有效时间
     */
    private Date sysTokenTime;
    
    private String sysTokenTimeShow;
    
    /**
     * sysToken有效小时数（default：2）
     */
    @Value("${token.valide.hours:2}")
    private Integer hours;
    
    @Value("${system.auto.login:false}")
    private Boolean autoLogin;
    
    /**
     * 验证token是否合法
     * 
     * @param token
     * @return
     * @return
     */
    public boolean valide(String token)
    {
        if (autoLogin)
        {
            return true;
        }
        boolean success = StringUtils.equals(token, getToken());
        if (!success)
        {
            log.info("------ now valid sysToken is： {}", sysToken);
        }
        return success;
    }
    
    /**
     * 获取sysToken有效时间
     * 
     * @return
     */
    public String getTokenTime()
    {
        return sysTokenTimeShow;
    }
    
    /**
     * 获取sysToken
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    private String getToken()
    {
        Date now = new Date();
        if (sysTokenTime == null || now.after(sysTokenTime))
        {
            sysToken = UUID.randomUUID().toString().replace("-", "");
            sysTokenTime = DateUtils.addHours(now, hours);
            sysTokenTimeShow = DateFormatUtils.format(sysTokenTime, "yyyy-MM-dd HH:mm:ss");
        }
        return sysToken;
    }
}
